package app.transmission.remote.connect;

import java.io.IOException;

import org.springframework.http.HttpBasicAuthentication;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.client.ClientHttpResponse;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.web.client.ResponseErrorHandler;
import org.springframework.web.client.RestTemplate;

import com.google.inject.Inject;
import com.google.inject.Singleton;

import android.app.Application;
import app.transmission.remote.common.TranSettings;

@Singleton
public class DaemonConnect {
	
	private TranSettings settings;
	
	private HttpHeaders requestHeaders;
	
	private MappingJackson2HttpMessageConverter messageConverter;
	
	private RestTemplate restTemplate;
	
	@Inject
	public DaemonConnect(Application application) {
		this.settings = (TranSettings) application;
		messageConverter = new MappingJackson2HttpMessageConverter();
		requestHeaders = new HttpHeaders();
		restTemplate = new RestTemplate();
		restTemplate.getMessageConverters().add(messageConverter);
	}
	
	public void startConnect () {
		requestHeaders.setAuthorization(new HttpBasicAuthentication(settings.getUser(), settings.getPassword()));
		
		RestTemplate sessionTemplate = new RestTemplate();
		HttpEntity<Object> requestEntity = new HttpEntity<Object>(requestHeaders);
		sessionTemplate.getMessageConverters().add(messageConverter);
		sessionTemplate.setErrorHandler(new ResponseErrorHandler() {
			@Override
			public boolean hasError(ClientHttpResponse response) throws IOException {
				if (response.getStatusCode() == HttpStatus.CONFLICT) {
					String sessionId = response.getHeaders().getFirst("X-Transmission-Session-Id");
					requestHeaders.add("X-Transmission-Session-Id", sessionId);
					return false;
				}
				return true;
			}
			@Override
			public void handleError(ClientHttpResponse response) throws IOException {
				
			}
		});
		sessionTemplate.put(settings.getUrl(), requestEntity);
	}
	
	public <T> T postResponse(Object request, Class<T> clazz) {
		HttpEntity<Object> requestEntity = new HttpEntity<Object>(request, requestHeaders);
		return restTemplate.postForObject(settings.getUrl(), requestEntity, clazz);
	}
	
	public <T> T getResponse(Class<T> clazz) {
		HttpEntity<Object> requestEntity = new HttpEntity<Object>(requestHeaders);
		return restTemplate.postForObject(settings.getUrl(), requestEntity, clazz);
	}
	
	public void putResponse(Object request) {
		HttpEntity<Object> requestEntity = new HttpEntity<Object>(request, requestHeaders);
		restTemplate.put(settings.getUrl(), requestEntity);
	}
	
}
